package com.zyj.java1;

import java.lang.ref.SoftReference;
import java.net.SocketTimeoutException;

/**
 * @program: JVMDemo
 * @ClassName SoftReferenceTest
 * @author: YaJun
 * @Date: 2022 - 01 - 26 - 9:27
 * @Package: com.zyj.java1
 * @Description:
 */
public class SoftReferenceTest {

    public static class User{
        private Integer id;
        private String name;

        public User(Integer id, String name) {
            this.id = id;
            this.name = name;
        }

        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
        }
    }


    public static void main(String[] args) {
        User user = new User(1, "jack");
        SoftReference<User> softReference = new SoftReference<User>(user);
        user = null;    // 取消强引用

        // 从软引用中重新获得引用对象
        System.out.println(softReference.get());

        System.gc();
        System.out.println("After GC...");
        System.out.println(softReference.get());    // 由于堆空间内存足够，不会回收软引用得对象

        try {
            // 让系统认为内存紧张
            byte[] b = new byte[1024 * 7168 - 613 * 1024];
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 再次从软引用中获取引用对象
            System.out.println(softReference.get()); // 在报OOM之前，垃圾回收期会回收软引用的可达对象
        }
    }

}
